<?php
class Season extends Page {

	static $has_written = false;

	static $db = array(
		'SeasonStarted' => 'Int'
		);

		static $has_many = array(
		'Leagues' => 'League'
		);

		function getCMSFields() {
			$fields = parent::getCMSFields();
			
            $le = new LeagueEditor($this,'Leagues','Ligen','');
            $ge = null;
			if ($this->SeasonStarted)
			{
				 $ge = new GameEditor($this,'Game','Spiele','');
			     $le->setReadonly(true);
			}
			else {
			     $fields->addFieldToTab("Root.Content.Ligen", new CheckboxField('startSeason','Saison starten',0));
			}
            $fields->addFieldToTab("Root.Content.Ligen", $le);
            if ($ge)
            $fields->addFieldToTab("Root.Content.Spiele", $ge);
            //
			return $fields;
		}

		function teams() {
			return DataObject::get('Team');
		}

		function onBeforeWrite() {
			parent::onBeforeWrite();

			if(!self::$has_written) {


				if (isset($_POST['createLeague']) && $_POST['createLeague'])
				{
					$newLeague = new League();
					$newLeague->SeasonID = $this->ID;
					$newLeague->write();
					FormResponse::add("$('Form_EditForm').getPageFromServer($this->ID);");
				}

				if (isset($_POST['startSeason']) && $_POST['startSeason'] == 1) {
					$allLeagues = $this->Leagues();
					foreach ($allLeagues AS $league) {
						$playTable = $this->getPlayTableForLeague($league);
						$roundsToPlay = $league->Teams()->Count() - 1;
						$teams = $league->Teams()->toArray();
						$round = 1;
						 
						foreach ($playTable AS $day) {
								
							foreach ($day AS $gameArray) {
								
								if (isset($teams[$gameArray[0]]) && isset($teams[$gameArray[1]]))
								{
									$game = new Game();
									$game->LeagueID = ($league->ID);
									$game->HomeTeamID = ($teams[$gameArray[0]]->ID);
									$game->GuestTeamID = ($teams[$gameArray[1]]->ID);
									$game->Round = $round;
									$game->GoalsHomeTeam = -1;
									$game->GoalsGuestTeam = -1;
									$game->write();
								/* keine rückrunde im foul modus!
								$game = new Game();
                                $game->LeagueID = ($league->ID);
                                $game->HomeTeamID = ($teams[$gameArray[1]]->ID);
                                $game->GuestTeamID = ($teams[$gameArray[0]]->ID);
                                $game->Round = $round + $roundsToPlay;
                                $game->GoalsHomeTeam = -1;
                                $game->GoalsGuestTeam = -1;
                                $game->write();
                                */
							}

							}
                    
				   $round++;
						}
                    
                    $league->updateTable();
					}
					$this->setReferees();
					FormResponse::add("$('Form_EditForm').getPageFromServer($this->ID);");		
					$this->SeasonStarted = 1;
				}
				self::$has_written = true;
			}
		}

		private function setReferees() {
			if ($this->Leagues()->count() == 1) {
			    $l = $this->Leagues()->First();
			    $res = DB::query('SELECT Max(round) From Game WHERE LeagueID = ' . $l->ID);
                $row = $res->nextRecord();
                $rounds = intval($row['Max(round)']);
                $teams = $l->Teams()->toArray();
                foreach ($teams AS $t) {
                	$assignCount[$t->ID] = 0;
                }
                $refCount = array();
                for ($i = 1; $i <= $rounds; $i++) {
                	$games = DataObject::get('Game','Round = '.$i.' AND LeagueID = ' .$l->ID,'ID');
                	$teamPool = array(array(),array());
                	$m = $games->count();
                	$c = 1;
                    foreach ($games AS $g) {
                        
                        if ($c <= $m) {
                            $teamPool[1][] = $g->HomeTeam();
                            $c++;
                        } else {
                            $teamPool[0][] = $g->HomeTeam();
                            $c++;
                        }
                        if ($c <= $m) {
                            $teamPool[1][] = $g->GuestTeam();
                            $c++;
                        }
                        else {
                            $teamPool[0][] = $g->GuestTeam();
                            $c++;
                        }
                    } 
                	
                    $amount = ($m % 2 == 0)?$m/2:intval($m/2)+1;
                	$assignTeams = $this->getMinAssignedRefereeTeam($amount,$teamPool[0],$assignCount);
                	$assignTeams = array_merge($assignTeams,$this->getMinAssignedRefereeTeam($amount,$teamPool[1],$assignCount));
                	
                	$c = 0;
                    $prevGame = null;
                    foreach ($games AS $g) {
                    	
                    	if ($g->HomeTeamID == $assignTeams[$c]->ID || $g->GuestTeamID == $assignTeams[$c]->ID) {
                    		$g->RefereeTeamID = $prevGame->RefereeTeamID;
                    		$prevGame->RefereeTeamID = $assignTeams[$c]->ID;
                    		$prevGame->write();
                    	} else {
                            $g->RefereeTeamID = $assignTeams[$c]->ID;
                    	}
                    	$g->write();
                        $prevGame = $g;
                        $assignCount[$assignTeams[$c]->ID]++;
                        $c++;
                    }
                	//var_dump($assignCount);
                }
			    
			    
			} else {
				$it = $this->Leagues()->getIterator();
				while ($c = $it->current()) {
					if (!$next = $it->peekNext()) {
						$next = $this->Leagues()->First();
					}
					$teamPool = $next->Teams();
					$assignCount = array();
				    foreach ($teamPool AS $t) {
                        $assignCount[$t->ID] = 0;
                    }
                    $res = DB::query('SELECT Max(round) From Game WHERE LeagueID = ' . $c->ID);
                    $row = $res->nextRecord();
                    $rounds = intval($row['Max(round)']);
                    
                    for ($i = 1; $i <= $rounds; $i++) {
	                    $games = DataObject::get('Game','Round = '.$i.' AND LeagueID = ' .$c->ID,'ID');
	                    $amount = $games->count();
	                    $assignTeams = $this->getMinAssignedRefereeTeam($amount,$teamPool,$assignCount);
	                    $j = 0;
	                    
	                    foreach ($games AS $g) { 
                            $g->RefereeTeamID = $assignTeams[$j]->ID;
                            $assignCount[$assignTeams[$j]->ID]++;
                            $g->write();
                            $j++;
	                    }
                    }
                $it->next();
				}
			}
		}
		
		private function getMinAssignedRefereeTeam($amount,$pool,$assignCount) {
			$refereeTeams = array();
			//var_dump($pool);
			foreach($pool AS $t) {
			     for ($i =0; $i < $amount;$i++) {
			     	if (!isset($refereeTeams[$i])) {
			     	   $refereeTeams[$i] = $t;
			     	   break;
			     	}

			     	if ($assignCount[$t->ID] < $assignCount[$refereeTeams[$i]->ID]) {
			     		$old = $refereeTeams[$i];
			     		$refereeTeams[$i] = $t;
			     		if ($i + 1 < $amount)
			     		    $refereeTeams[$i+1] = $old;
			     		break;
			     	}
			     }
			}
			return $refereeTeams;
		}
		
		private function getPlayTableForLeague($league) {
			$result = array ();
			$n = $league->Teams()->count();
			// check if teams count is a even one
			if ($n % 2 != 0) {
				$n++;
			}
			if ($n % 2 == 0) {
				for ($r = 0; $r < $n - 1; $r++) {
					for ($i = 0; $i < $n / 2; $i++) {
						if ($r % 2 == 0) {
							$result[$r][] =
							array (
							($i == 0 ? 0:($r + $i) % ($n - 1) + 1),
							($n - 1 + $r - $i) % ($n - 1) + 1,
							);
						} else {
							$result[$r][] =
							array (
							($n - 1 + $r - $i) % ($n - 1) + 1,
							($i == 0 ? 0:($r + $i) % ($n - 1) + 1)
							);
						}

					}
				}
			}
			return $result;
		}

}

class Season_Controller extends Page_Controller {
	
	private $leagueId = -1;
	
    public static $url_handlers = array(
            ''=> 'index',
            'ShowLeague/$ID' =>'ShowLeague'
            );
	
	function index() {
		return $this->render();
	}
            
	function init(){
		// block prototype validation
		Validator::set_javascript_validation_handler('none');
		// load the jquery
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/plugins/validate/jquery.validate.min.js');
		      //Requirements::javascript('leaguemanager/javascript/Season.js');
		
		parent::init();
	}

	
	
	function SelectedLeague() {
		if ($this->leagueId > -1)
			$league = DataObject::get_one('League','`League`.ID = '.$this->leagueId. ' AND SeasonID = ' .$this->ID,'ID');
		else 
		$league = DataObject::get_one('League','SeasonID = ' .$this->ID,'ID');
		return $league;
	}
	
	
	
	function ShowLeague($request) {
		$this->leagueId = intval($request->param('ID'));
		$league = $this->SelectedLeague();
		return $league->TableResults();
	}
	
	function ShowSchedule($request) {
	    $this->leagueId = intval($request->param('ID'));
        $league = $this->SelectedLeague();
        return $league->Schedule();	
	}


}

?>